<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel单选题生成器</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container mt-5">
        <h2 class="mb-3">Excel单选题生成器</h2>
        <div id="exampleTableContainer" class="mb-3"></div>
        <div class="mb-2">
            <input type="file" class="form-control" id="excelFile" accept=".xlsx,.xls">
        </div>
        <div class="mb-2">
            <input type="text" class="form-control" id="sheetNameInput" placeholder="输入表名（可选）">
        </div>
        <div class="mb-2">
            <input type="text" class="form-control" id="questionColumnsInput" placeholder="输入问题列（默认为第1列，多列用任意符号分割）"
                value="1">
        </div>
        <div class="mb-2">
            <input type="text" class="form-control" id="answerColumnsInput" placeholder="输入答案列（默认为第2列，多列用任意符号分割）"
                value="2">
        </div>
        <div class="mb-2">
            <button class="btn btn-primary w-100" id="generateQuestionsBtn">生成单选题</button>
        </div>
        <div class="mb-2">
            <button class="btn btn-primary w-100" id="generateExampleTableBtn">生成示例表格</button>
        </div>
        <div id="questionsContainer" class="mb-5"></div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            // 从localStorage加载保存的值
            const savedQuestionColumns = localStorage.getItem('questionColumns') || '1';
            const savedAnswerColumns = localStorage.getItem('answerColumns') || '2';
            const savedSheetName = localStorage.getItem('sheetName') || '';

            document.getElementById('questionColumnsInput').value = savedQuestionColumns;
            document.getElementById('answerColumnsInput').value = savedAnswerColumns;
            document.getElementById('sheetNameInput').value = savedSheetName;

            // 绑定按钮点击事件
            document.getElementById('generateQuestionsBtn').addEventListener('click', generateQuestions);
            document.getElementById('generateExampleTableBtn').addEventListener('click', generateExampleTable);

            // 添加文件选择改变时的事件监听器
            document.getElementById('excelFile').addEventListener('change', handleFileChange);
            // 修改sheetName的事件监听器为blur
            document.getElementById('sheetNameInput').addEventListener('blur', handleSheetBlur);

            // 保存输入框值到localStorage当输入框失去焦点时
            document.getElementById('questionColumnsInput').addEventListener('blur', saveInputValue);
            document.getElementById('answerColumnsInput').addEventListener('blur', saveInputValue);
            document.getElementById('sheetNameInput').addEventListener('blur', saveInputValue);
        });

        // 文件选择改变时处理函数
        function handleFileChange() {
            generateQuestions();
            generateExampleTable();
        }

        // sheetName输入框失去焦点时处理函数
        function handleSheetBlur() {
            generateQuestions();
            generateExampleTable();
        }

        // 保存输入框值到localStorage
        function saveInputValue(event) {
            localStorage.setItem(event.target.id, event.target.value);
        }

        // 生成单选题函数
        function generateQuestions() {
            const fileInput = document.getElementById('excelFile');
            const sheetName = document.getElementById('sheetNameInput').value;
            const questionColumns = parseColumns(document.getElementById('questionColumnsInput').value);
            const answerColumns = parseColumns(document.getElementById('answerColumnsInput').value);

            if (!fileInput.files.length) {
                alert('请先选择一个Excel文件。');
                return;
            }

            const reader = new FileReader();
            reader.onload = function (e) {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const sheetNameToUse = sheetName || workbook.SheetNames[0];
                const sheet = workbook.Sheets[sheetNameToUse];
                const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: "" });

                // 移除空行
                rows.splice(-1, 1);

                const nonEmptyRows = rows.filter(row => row.every(cell => cell !== ""));
                if (nonEmptyRows.length === 0) {
                    alert('表格中没有有效数据。');
                    return;
                }

                const shuffledRows = shuffleArray(nonEmptyRows);
                const questionSet = shuffledRows.slice(0, 5); // 取前5行作为问题集
                const correctAnswerIndex = Math.floor(Math.random() * questionSet.length); // 随机选择一行作为正确答案
                const correctAnswer = questionSet[correctAnswerIndex];

                let questionsHTML = '';

                // 拼接问题列的内容
                const questionText = `<strong>Q1: ${questionColumns.map(col => correctAnswer[col - 1]).join(', ')}</strong>`;
                questionsHTML += `<div class="card card-body mb-3">${questionText}</div>`;

                answerColumns.forEach((answerColumn, index) => {
                    if (answerColumn > correctAnswer.length || answerColumn <= 0) {
                        console.warn(`答案列${answerColumn}不存在，已被忽略。`);
                        return; // 忽略不存在的答案列
                    }

                    const shuffledQuestionSets = shuffleArray(questionSet);
                    const radioGroupHTML = shuffledQuestionSets.map((row, idx) => {
                        return `
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="radio" name="answer${index}" value="${row[answerColumn]}" id="answer${index}-${idx}"
                               data-answer-column="${answerColumn}">
                        <label class="form-check-label" for="answer${index}-${idx}">
                            ${row[answerColumn]}　
                            <span class="text-primary d-none" data-question-text="${questionColumns.map(col => row[col - 1]).join(', ')}">${questionColumns.map(col => row[col - 1]).join(', ')}</span>
                        </label>
                    </div>
                `;
                    }).join('');

                    questionsHTML += `<div class="mb-3">${radioGroupHTML}</div>`;
                    questionsHTML += `<div class="feedback text-danger" id="feedback-${answerColumn}">请选择答案</div>`;
                });

                document.getElementById('questionsContainer').innerHTML = questionsHTML;

                // 添加单选按钮事件监听器
                const radios = document.querySelectorAll('input[type="radio"]');
                radios.forEach(radio => {
                    radio.addEventListener('change', function () {
                        const feedbackElement = document.getElementById(`feedback-${this.getAttribute('data-answer-column')}`);
                        const selectedAnswer = this.value;
                        const answerColumnIndex = parseInt(this.getAttribute('data-answer-column'), 10);
                        const isCorrect = selectedAnswer === correctAnswer[answerColumnIndex];
                        feedbackElement.textContent = isCorrect ? '正确答案！' : '错误答案！';
                        feedbackElement.className = `feedback text-${isCorrect ? 'success' : 'danger'}`;

                        // 检查所有反馈是否都是“正确答案！”
                        const allFeedbacks = document.querySelectorAll('.feedback');
                        let allCorrect = true;
                        allFeedbacks.forEach(feedback => {
                            if (feedback.textContent !== '正确答案！') {
                                allCorrect = false;
                            }
                        });

                        // 如果不是所有答案都正确，则隐藏text-primary
                        const hiddenElements = document.querySelectorAll('.text-primary');
                        hiddenElements.forEach(element => {
                            element.classList.toggle('d-none', !allCorrect);
                        });
                    });
                });
            };
            reader.readAsArrayBuffer(fileInput.files[0]);
        }

        // 生成示例表格函数
        function generateExampleTable() {
            const fileInput = document.getElementById('excelFile');
            const sheetName = document.getElementById('sheetNameInput').value;

            if (!fileInput.files.length) {
                document.getElementById('exampleTableContainer').innerHTML = '<div class="alert alert-danger">请先选择一个Excel文件。</div>';
                return;
            }

            const reader = new FileReader();
            reader.onload = function (e) {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const sheetNameToUse = sheetName || workbook.SheetNames[0];
                const sheet = workbook.Sheets[sheetNameToUse];
                const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: "" });

                if (rows.length <= 1) {
                    document.getElementById('exampleTableContainer').innerHTML = '<div class="alert alert-danger">表格中没有有效数据。</div>';
                    return;
                }

                const nonEmptyRows = rows.filter(row => row.every(cell => cell !== ""));
                if (nonEmptyRows.length === 0) {
                    document.getElementById('exampleTableContainer').innerHTML = '<div class="alert alert-danger">表格中没有有效数据。</div>';
                    return;
                }

                const shuffledRows = shuffleArray(nonEmptyRows);
                const randomRow = shuffledRows[0];

                const headers = Array.from({ length: randomRow.length }, (_, i) => i + 1); // 标题为1到n的序号
                const tableBodyHTML = `
            <tr>
                ${randomRow.map(cell => `<td>${cell}</td>`).join('')}
            </tr>
        `;

                const exampleTableHTML = `
            <div style="max-height: 300px; overflow-x: auto;">
                <table class="table table-bordered table-striped">
                    <thead class="table-dark">
                        <tr>
                            ${headers.map(header => `<th scope="col">${header}</th>`).join('')}
                        </tr>
                    </thead>
                    <tbody>
                        ${tableBodyHTML}
                    </tbody>
                </table>
            </div>
        `;

                document.getElementById('exampleTableContainer').innerHTML = exampleTableHTML;
            };
            reader.readAsArrayBuffer(fileInput.files[0]);
        }

        // 随机打乱数组顺序
        function shuffleArray(arr) {
            for (let i = arr.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [arr[i], arr[j]] = [arr[j], arr[i]];
            }
            return arr;
        }

        // 解析输入列字符串为数字数组
        function parseColumns(input) {
            return input.split(/\W+/).map(column => parseInt(column.trim(), 10)).filter(column => !isNaN(column));
        }
    </script>
</body>

</html>